package com.huwaiwai.nio.demo02;

import com.huwaiwai.nio.utils.ChannelUtils;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 分散（scatter）
 * 从Channel中读取是指在读操作时将读取的数据写入多个buffer中。
 * 因此，Channel将从Channel中读取的数据分散（scatter）到多个Buffer中
 * Created by huweiwei on 2017/4/20.
 */
public class ScatteringReads {
    public static void main(String [] args) throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("C:\\test\\src\\main\\java\\com\\huwaiwai\\nio\\file\\nio-data.txt", "rw");
        FileChannel channel = accessFile.getChannel();

        ByteBuffer hello = ByteBuffer.allocate(5);
        ByteBuffer world = ByteBuffer.allocate(5);

        //将两个buffer插入数组
        ByteBuffer [] buffers = {hello, world};
        //用buffer数组读取，当第一个buffer充满后才会转到第二个buffer
        channel.read(buffers);

        //分别打印两个buffer
        System.out.println(ChannelUtils.read(hello));
        System.out.println(ChannelUtils.read(world));
        accessFile.close();
    }
}
